<template>
	<div class="upload-file flex-y-start">
		<el-upload :multiple="false" :show-file-list="false" action="#" :on-success="handleImageSuccess"
			:http-request="uploadImage" :before-upload="beforeUpload" :on-preview="handlePictureCardPreview"
			class="image-uploader" drag>
			<img v-if="imgUrl" :src="imgUrl" class="avatar">
			<div v-else>
				<i class="el-icon-plus" />
				<!-- <div class="el-upload__text">
					将文件拖到此处，或<em>点击上传</em>
				</div> -->
			</div>

		</el-upload>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
		<div class="tip" v-if="tip">{{ tip }}</div>
	</div>
</template>

<script>
const allowType = [
	'image/png',
	'image/jpg',
	'image/jpeg',
]

export default {
	props: {
		tip: {
			type: String,
			default: ''
		},
		value: {

		}
	},
	data() {
		return {
			imgUrl: '',
			dialogImageUrl: '',
			dialogVisible: false,
      response:'',
      file:'',
      fileList:''
		}
	},
	watch: {
		value: {
			handler: function (val) {
				if (typeof val === 'string' && val.startsWith('http')) {
					this.imgUrl = val
				}
				if(!val){
					this.imgUrl = ''
				}
			},
			immediate: true,
		}
	},
	methods: {
		handleImageSuccess(response,file,fileList) { },
		uploadImage(file) {
			let fr = new FileReader();
			fr.onload = () => {
				this.imgUrl = fr.result;
			};
			fr.readAsDataURL(file.file);
			this.$emit('update:value', file.file);
		},
		beforeUpload(file) {
			const isImg = allowType.includes(file.type);
			if (!isImg) {
				this.$message.error('只能传入图片');
				return false;
			};
			return isImg
		},
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.dialogVisible = true;
		}
	}
}
</script>

<style lang="scss" scoped>
.image-uploader {
	width: 194px;
	border-radius: 4px;
	margin-right: 30px;

	.el-icon-plus {
		font-size: 40px;
		color: #E0E0E0;
	}

	>>>.el-upload-dragger {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 135px;
		height: 156px;
		border: 1px solid #E0E0E0;
		border-radius: 4px;
	}

	>>>.el-upload-dragger:hover {
		border: 1px solid #C0C4CC;
	}

	.avatar {
		width: 194px;
		height: 232px;
		object-fit: contain;
	}

}

.tip {
	font-size: 14px;
	font-weight: 400;
	color: #666666;
	margin-right: 30px;
}
</style>
